package com.hmdp.utils;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;


@Component
public class RedisIdWorker {


    private static final int COUNT_BITS = 32;
    private static final LocalDateTime BEGIN_DATE = LocalDateTime.of(2020, 1, 1, 0, 0);
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    public long nextId(String prefix) {

        //1.生成时间戳
        long now = LocalDateTime.now().toEpochSecond(ZoneOffset.UTC);
        long beginDate = BEGIN_DATE.toEpochSecond(ZoneOffset.UTC);
        long timeStamp = now - beginDate;
        //2.生成序列号
        String date = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy:MM:dd"));
        long count = stringRedisTemplate.opsForValue().increment("icr:" + prefix + ":" + date);
        //3.拼接并返回
        return timeStamp << COUNT_BITS | count;
    }
}
